const express = require('express')
const bodyParser = require('body-parser')
const home = express.Router()
const { Article } = require('../model/article')
const { Comment } = require('../model/comment')
const { User } = require('../model/user')
const pagination = require('mongoose-sex-page')
home.use(bodyParser.urlencoded({ extended: false }))

home.get(['/', '/index'], async (req, res) => {
  let { id } = req.query
  let { page } = req.query
  let writer
  if (id) {
    writer = await User.findOne({ _id: id })
  }
  let result = await pagination(Article).
    find().
    populate('writer').
    page(page).
    size(4).
    display(5).
    exec()
  // console.log(result)
  res.render('home/default', {
    result,
    writer
  })
})

home.get('/article', async (req, res) => {
  let { id } = req.query
  let comment = await Comment.find({ aid: id }).populate('uid')
  let result = await Article.findOne({ _id: id }).populate('writer')
  res.render('home/article', {
    result,
    comment
  })
})

home.post('/comment', (req, res) => {
  const { content, uid, aid } = req.body
  Comment.create({
    content: content,
    uid: uid,
    aid: aid,
    time: new Date()
  })
  res.redirect(`/home/article?id=${aid}`)
})

module.exports = home
